package com.ucas.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisUtil {
	private static final String IP = "10.0.1.153"; // ip
    private static final int PORT = 6379;         // 端口
    private static int   MAX_ACTIVE = 1024;       // 最大连接数
    private static int   MAX_IDLE = 200;          // 设置最大空闲数
    private static int   MAX_WAIT = 10000;        // 最大连接时间
    private static int   TIMEOUT = 10000;         // 超时时间
    private static boolean BORROW = true;         // 在borrow一个事例时是否提前进行validate操作
    private static JedisPool pool = null;
    
    /**
     * 初始化线程池
     */
    static{
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(MAX_ACTIVE);
        config.setMaxIdle(MAX_IDLE);
        config.setMaxWaitMillis(MAX_WAIT);
        config.setTestOnBorrow(BORROW);
        pool = new JedisPool(config, IP, PORT, TIMEOUT);
        System.out.println("初始化JedisPool完成");
    }
    /**
     * 获取连接
     */
    public static synchronized  Jedis getJedis(){
        try{
            if(pool != null)
                return pool.getResource();
            else
                return null;
        }catch (Exception e) {
        	e.printStackTrace();
            return null;
        }
    }
    /**
     * @Description:设置失效时间
     * @param @param key
     * @param @param seconds
     * @param @return 
     * @return boolean 返回类型
     */
    public static void disableTime(String key,int seconds){
        Jedis jedis = null;
        try{
            jedis = getJedis();
            jedis.expire(key, seconds);
        }catch (Exception e) {
        	
        }finally {
        	returnResource(jedis);
        }
    }
    /**
     * @Description: 关闭连接
     * @param @param jedis 
     * @return void 返回类型
     */
    public static void returnResource(Jedis jedis){
        if(jedis != null) {
        	jedis.close();
        }
    }
}
